package com.cy.store.controller;

import com.cy.store.entity.Address;
import com.cy.store.service.IAddressService;
import com.cy.store.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2022-12-05 19:05
 */
@Slf4j
@RestController
@RequestMapping("/addresses")
public class AddressController extends BaseController{
    @Autowired
    private IAddressService addressService;

    /**
     * 添加地址信息
     * @param address
     * @param session
     * @return
     */
    @PostMapping("/add_new_address")
    public JsonResult<Void> addNewAddress(Address address, HttpSession session){
        // 调用业务层方法
        addressService.addNewAddress(getUidFromSession(session), getUsernameFromSession(session), address);

        // 返回成功
        return new JsonResult<>(OK);
    }

    /**
     * 根据用户id获取地址信息
     * @param session
     * @return
     */
    @GetMapping({"/",""})
    public JsonResult<List<Address>> getByUid(HttpSession session){
        // 获取uid
        Integer uid = getUidFromSession(session);
        List<Address> data = addressService.getByUid(uid);

        // 向前端返回数据
        return new JsonResult<>(OK, data);
    }

    /**
     * 获取对应aid的address信息
     * @param aid
     * @return
     */
    @GetMapping("/{aid}")
    public JsonResult<Address> getByAid(@PathVariable("aid") Integer aid){
        Address data = addressService.getByAid(aid);
        return new JsonResult(OK,data);
    }
    /**
     * 修改默认地址信息
     * @param aid
     * @param session
     * @return
     */
    @PostMapping("/set_default/{aid}")
    public JsonResult<Void> setDefault(@PathVariable("aid") Integer aid,
                                        HttpSession session){
        // 调用业务层方法
        addressService.setDefault(aid, getUidFromSession(session), getUsernameFromSession(session));
        return new JsonResult<>(OK);
    }

    /**
     * 根据aid删除地址信息
     * @param aid
     * @param session
     * @return
     */
    @PostMapping("/delete/{aid}")
    public JsonResult<Void> delete(@PathVariable("aid") Integer aid, HttpSession session){
        // 调用业务层方法
        addressService.deleteByAid(aid,getUidFromSession(session),getUsernameFromSession(session));
        return new JsonResult<>(OK);
    }

    @PostMapping("/update")
    public JsonResult<Void> update(Address address,
                                   HttpSession session){
        log.info("address={}",address);
        // 调用业务层更新方法
        addressService.updateByAid(address,
                getUidFromSession(session),
                getUsernameFromSession(session));

        // 返回
        return new JsonResult(OK);
    }

}
